<template>
  <q-page>
    <div class="ocr-id-card row fit q-pa-xl">
      <div class="col flex flex-center box-content">
        <img :src="img" v-if="img" />
        <q-file v-else ref="fileField" filled v-model="uploadField" label="点击或者拖拽培训合格证正面到此处" input-style="height:200px;width:300px" :max-files="1"
          @input="fileChange">
          <template v-slot:prepend>
            <q-icon name="attach_file" />
          </template>
        </q-file>
      </div>
      <div class="col column bg-grey-1">
        <q-card class="q-ma-md q-ma-xl">
          <q-list bordered class="card-info">
            <q-item>
              <q-item-section>姓名：</q-item-section>
              <q-item-section>
                {{ idCard.name }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>国籍：</q-item-section>
              <q-item-section>
                {{ idCard.nationality }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>出生日期：</q-item-section>
              <q-item-section>
                {{ idCard.born }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>性别：</q-item-section>
              <q-item-section>
                {{ idCard.sex }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>证书编号：</q-item-section>
              <q-item-section>
                {{ idCard.id }}
              </q-item-section>
            </q-item>
            <q-separator />
            <q-item>
              <q-item-section>签发日期：</q-item-section>
              <q-item-section>
                {{ idCard.awardedDate }}
              </q-item-section>
            </q-item>
          </q-list>
          <q-table title="合格证列表" :data="certificateList" :columns="columns" row-key="title" hide-bottom :rows-per-page-options="[0]" />
        </q-card>

      </div>
    </div>
  </q-page>
</template>

<script>
import { imageOcr } from 'boot/api/index';
import { fileToBase64 } from 'components/utils/FileCompress';

export default {
  props: {},
  data() {
    return {
      uploadField: null,
      img: '',
      idCard: {
        id: '',
        name: '',
        sex: '',
        nationality: '',
        nation: '',
        address: '',
        born: '',
        awardedDate: '',
      },
      idCardEmpty: {
        id: '',
        name: '',
        sex: '',
        nationality: '',
        nation: '',
        address: '',
        born: '',
        awardedDate: '',
      },
      title: '',
      clause: '',
      dateIssue: '',
      dateExpiry: '',
      columns: [{
        name: 'title', label: '合格证名称', field: 'title', align: 'left',
      },
      {
        name: 'clause', label: '适用公约条款', field: 'clause', align: 'left',
      },
      {
        name: 'dateIssue', label: '签发日期', field: 'dateIssue', align: 'left',
      },
      {
        name: 'dateExpiry', label: '有效期至', field: 'dateExpiry', align: 'left',
      }],
      certificateList: [],
    };
  },
  computed: {},
  methods: {
    filterEn(value) {
      return value.replace(/[u4e00-u9fa5|,]+/ig, ' ');
    },
    trimColon(str) {
      if (str.indexOf(':') > -1) {
        [, str] = str.split(':');
      }
      if (str.indexOf('：') > -1) {
        [, str] = str.split('：');
      }
      return str;
    },
    trimNotCn(str) {
      return str.replace(/[u4e00-u9fa5|,]+/ig, '');
    },
    getDate(str) {
      str = this.trimColon(str);
      let date = `${str.split('日')[0]}日`;
      if (date.length > 11) {
        date = date.substring(date.length - 11);
      }
      return date;
    },
    // 判断字符串是否全是中文
    isAllChinese(str) {
      return /^[\u4E00-\u9FA5]+$/.test(str);
    },
    saxCertificateList(data) {
      let found = false;
      const keywordList = ['Date of Issue', 'Clause', 'Title of the Certificate(s)', 'Date of Expiry'];
      let certificate = {
        title: '', clause: '', dateIssue: '', dateExpiry: '',
      };
      for (let i = 0; i < data.length; i += 1) {
        const field = data[i];
        const { text } = field;
        if (keywordList.indexOf(text) > -1) {
          found = true;
        } else if (found) {
          // 如果有年月日   以VI开头  或者全是中文   精通教生艇筱和救助艇培训 那么就是我们想要的
          if (text.indexOf('年') > -1 && text.indexOf('月') > -1 && text.indexOf('日') > -1) {
            if (text.length === 22) {
              const [dateIssue, dateExpiry] = text.split('日');
              certificate.dateIssue = `${dateIssue}日`;
              certificate.dateExpiry = `${dateExpiry}日`;
            } else if (!certificate.dateIssue) {
              certificate.dateIssue = text;
            } else {
              certificate.dateExpiry = text;
            }
          } else if (text.indexOf('A-V') > -1) {
            if (text.indexOf('V') !== 0) {
              certificate.clause = `V${text.substring(1)}`;
            } else {
              certificate.clause = text;
            }
          } else if (this.isAllChinese(text)) {
            certificate.title = text;
          }
          // 获取全了，就换一个
          if (certificate.title && certificate.clause && certificate.dateExpiry && certificate.dateIssue) {
            this.certificateList.push({ ...certificate });
            certificate = {};
          }
        }
      }
    },
    fileChange() {
      const startTime = new Date().getTime();
      fileToBase64(this.uploadField, (base64) => {
        this.img = base64;
        const base64String = base64.replace('data:', '').replace(/^.+,/, '');
        imageOcr('/predict/ch_pp-ocrv3', { images: [base64String] }).then((rs) => {
          this.idCard = { ...this.idCardEmpty };
          if (rs.status === '000') {
            const { results } = rs;
            const result = results[0];
            const { data } = result;
            let all = '';
            for (let i = 0; i < data.length; i += 1) {
              const field = data[i];
              const { text } = field;
              all += text;
            }
            this.saxCertificateList(data);
            const idIdx = all.indexOf('No.');
            const nameIdx = all.indexOf('持证人姓名：');
            const enNameIdx = all.indexOf('Full name of the holder:');
            const sexIdx = all.indexOf('Gender:');
            const nationalityIdx = all.indexOf('Nationality');
            const bornIdx = all.indexOf('出生日期');
            const awardedDateIdx = all.indexOf('签发日期');
            const signatureIdx = all.indexOf('持证人签名');
            if (idIdx > -1 && nameIdx > -1 && sexIdx > -1 && enNameIdx > -1 && nationalityIdx > -1 && bornIdx > -1 && awardedDateIdx > -1 && signatureIdx > -1) {
              this.idCard.name = all.substring(nameIdx + 6, enNameIdx);
              this.idCard.sex = all.substring(sexIdx + 7, sexIdx + 8);
              this.idCard.nationality = this.filterEn(all.substring(nationalityIdx + 11, bornIdx));
              this.idCard.born = this.getDate(all.substring(bornIdx + 18, sexIdx - 3));
              this.idCard.awardedDate = this.getDate(all.substring(awardedDateIdx + 12, signatureIdx));
              this.idCard.id = this.trimColon(all.substring(idIdx + 3, awardedDateIdx));
            } else {
              if (nameIdx > -1 && enNameIdx > -1) {
                this.idCard.name = all.substring(nameIdx + 6, enNameIdx);
              }
              if (sexIdx > -1) {
                this.idCard.sex = all.substring(sexIdx + 7, sexIdx + 8);
              }
              if (nationalityIdx > -1 && bornIdx > -1) {
                this.idCard.nationality = this.filterEn(all.substring(nationalityIdx + 11, bornIdx));
              }
              if (sexIdx > -1 && bornIdx > -1) {
                this.idCard.born = this.getDate(all.substring(bornIdx + 19, sexIdx - 3));
              }
              if (awardedDateIdx > -1 && signatureIdx > -1) {
                this.idCard.awardedDate = this.getDate(all.substring(awardedDateIdx + 12, signatureIdx));
              }
              if (idIdx > -1 && awardedDateIdx > -1) {
                this.idCard.id = all.substring(idIdx + 15, awardedDateIdx);
              }
              // this.$q.notify({
              //   textColor: 'red',
              //   timeout: 24 * 3600 * 1000,
              //   message: `解析失败，服务器返回内容：[${all}]`,
              //   position: 'top',
              // });
            }
            if (this.idCard.sex !== '男' && this.idCard.sex !== '女') {
              this.idCard.sex = all.indexOf('男') > -1 ? '男' : '女';
            }
            // 名字可能打印的靠上
            if (!this.idCard.name) {
              const publicOfChinaIdx = all.indexOf('PUBLICOFCHINA');
              const holderNameIdx = all.indexOf('持证人姓名');
              if (publicOfChinaIdx > -1 && holderNameIdx > -1) {
                this.idCard.name = all.substring(publicOfChinaIdx + 13, holderNameIdx);
              }
            }
            if (!this.idCard.nationality) {
              const nameHolderIdx = all.indexOf('Full name of the holder');
              const nationaIdx = all.indexOf('国籍');
              if (nameHolderIdx > -1 && nationaIdx > -1) {
                let nationality = all.substring(nameHolderIdx, nationaIdx);
                nationality = this.trimColon(nationality);
                this.idCard.nationality = this.trimNotCn(nationality);
              }
            }
            const endTime = new Date().getTime();
            this.$q.notify({
              message: `耗时：${(endTime - startTime) / 1000}秒`,
              position: 'bottom',
            });
          }
        });
      });
    },
  },
  created() { },
  mounted() {
  },
  watch: {
  },
};
</script>
<style lang="stylus">
.ocr-id-card
  .box-content
    overflow: hidden;
    background-color: #ececec;
    img
      width 100%
      height 100%
  .card-info
    .q-item
      div:first-child
        max-width 150px !important
        padding-left 20px

</style>
